package com.association.utils;

import org.apache.commons.codec.binary.Base64;
import org.springframework.util.DigestUtils;

import java.security.MessageDigest;

/**
 * Created by admin on 2015/7/6.
 */
public class Md5Util {
    private static final String charset = "UTF-8";

    public static String encryptMd5(String content, String parternId) throws Exception {
        return new String(Base64.encodeBase64(DigestUtils.md5Digest((content + parternId).getBytes(charset))), charset);
    }

    public static String md5Encode(String source) {
        if(source == null) return null;
        try {
            String res = new String(source);
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = md.digest(res.getBytes("UTF-8"));
            StringBuffer stringBuffer = new StringBuffer(bytes.length * 2);
            for (int i = 0; i < bytes.length; i++) {
                if ((bytes[i] & 0xff) < 0x10) {
                    stringBuffer.append("0");
                }
                stringBuffer.append(Long.toString(bytes[i] & 0xff, 16));
            }
            return stringBuffer.toString();
        } catch (Exception e) {
            return null;
        }
    }

    public static void main(String[] args) {
        String str="123456";
        System.out.println(md5Encode(str));

    }
}
